//
//  OppoinViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/9/13.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "OppoinViewController.h"
#import "UIColor+Hex.h"
#import "OppiontmentViewController.h"
#import "MBProgressHUD+MJ.h"
#import "UserDefaultUtil.h"
#import "HttpReauestParam.h"
#import "AFHTTPRequestOperationManager.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapFoundationKit/AMapServices.h>
#import <AMapLocationKit/AMapLocationKit.h>
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试
@interface OppoinViewController ()

@property float lat;
@property float lon;

@end

@implementation OppoinViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // Do any additional setup after loading the view.
     self.note_text.delegate = self;
    self.limitBtn.enabled = NO;
    
    [self.limitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.limitBtn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#ff7e00"]] forState:UIControlStateNormal];
    [self.limitBtn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#55ff7e00"]] forState:UIControlStateSelected];
    [self.limitBtn addTarget:self action:@selector(limitBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    OppiontmentViewController *timeView = [[OppiontmentViewController alloc] init];
//    timeView.view.frame = CGRectMake(0, ScreenHeight - 260, ScreenWidth, 260);
//    timeView.view.hidden = YES;
//    timeView.view.tag = 111;
//    [self.view addSubview:timeView.view];
    
    [self initPickView];
    
    [self initCompleteBlock];
    [self configLocationManager];
}
- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置不允许系统暂停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    //设置允许在后台定位
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    
    //设置定位超时时间
    //[self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    //[self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    //进行单次定位请求
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}
- (void)initCompleteBlock
{
    __weak OppiontmentViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            //如果为定位失败的error，则不进行annotation的添加
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        //得到定位信息，添加annotation
        if (location)
        {
            _lat = location.coordinate.latitude;
            _lon = location.coordinate.longitude;
        }
    };
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)button_click:(id)sender {
    
    UIView * view = sender;
    if(view.tag == 11){
        //返回键
        [self.navigationController popViewControllerAnimated:YES];
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return theImage;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self.note_text resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}


- (IBAction)view_touch:(id)sender {
   
    
    
    [self.view endEditing:YES];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)showTimeView:(id)sender {
    
    UIView *timeView = [self.view viewWithTag:111];
    if (timeView.hidden) {
        timeView.hidden = NO;
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            timeView.frame = CGRectMake(0, ScreenHeight - 260, ScreenWidth, 260);
        }];
        
    }else{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            timeView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 260);
            timeView.hidden = YES;
        }];
       
        
    }
}


-(NSInteger)initData{
    
    NSInteger result = 0;
    NSDate * date = [NSDate date];
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSCalendarUnitMonth | NSCalendarUnitDay;
    
    comps = [calendar components:unitFlags fromDate:date];
    
    int year = [comps year];
    
    int month = [comps month];
    
    int day = [comps day];
    
    NSLog(@"month= %i,day=%i",month,day);
    
    NSArray * array1 = @[[NSString stringWithFormat:@"%i",year],[NSString stringWithFormat:@"%i",year + 1]];
    
    NSMutableArray *monthDay = [[NSMutableArray alloc]init];
    int count = 0;
    for (int i = 1; i <= 12; i++) {
        
        if (i == 4 || i == 6 || i == 9 || i == 11) {
            for (int j=1; j <= 30; j++) {
                if (i==month && j == day) {
                    result = count;
                }
                [monthDay addObject:[NSString stringWithFormat:@"%i月%i日",i,j]];
                count++;
            }
        }else if(i == 2){
            for (int j=1; j <= 29; j++) {
                if (i==month && j == day) {
                    result = count;
                }
                [monthDay addObject:[NSString stringWithFormat:@"%i月%i日",i,j]];
                count++;
            }
        }else{
            for (int j=1; j <= 31; j++) {
                if (i==month && j == day) {
                    result = count;
                }
                [monthDay addObject:[NSString stringWithFormat:@"%i月%i日",i,j]];
                count++;
            }
        }
    }
    NSMutableArray *timeArray = [[NSMutableArray alloc]init];
    
    
    for (int i = 0; i < 24; i++) {
        if (i == 0) {
            [timeArray addObject:[NSString stringWithFormat:@"00:00"]];
        }else{
            [timeArray addObject:[NSString stringWithFormat:@"%i:00",i]];
        }
        [timeArray addObject:[NSString stringWithFormat:@"%i:15",i]];
        
        [timeArray addObject:[NSString stringWithFormat:@"%i:30",i]];
        [timeArray addObject:[NSString stringWithFormat:@"%i:45",i]];
    }
    NSLog(@"%lu",array1.count);
    NSLog(@"%lu",monthDay.count);
    NSLog(@"%lu",timeArray.count);
    
    
    self.dataArray = @[array1,monthDay,timeArray];
    
    return result;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    NSLog(@"numberOfComponentsInPickerView");
    return self.dataArray.count;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSLog(@"numberOfRowsInComponent");
    NSArray * array = [self.dataArray objectAtIndex:component];
    
    return array.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSArray * array = [self.dataArray objectAtIndex:component];
    
    NSString *s = [array objectAtIndex:row];
    
    return s;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSLog(@"%@",self.dataArray[component][row]);
    
    if (component == 0) {
        self.myear = self.dataArray[component][row];
    }
    if (component == 1) {
        self.monthDay = self.dataArray[component][row];
    }
    if (component == 2) {
        self.mTime = self.dataArray[component][row];
    }
    
}

//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
//{
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12.0f, 0.0f, [pickerView rowSizeForComponent:component].width - 12, [pickerView rowSizeForComponent:component].height)] ;
//
//    label.text = self.dataArray[component][row];
//    label.backgroundColor = [UIColor clearColor];
//    label.textColor = [UIColor blackColor];
//    //[label setTextAlignment:UITextAlignmentCenter];
//    return label;
//}



- (void)initPickView{
    //初始化数据
    int result  = [self initData];
    
    UIView *dialogView = [[UIView alloc]initWithFrame: CGRectMake(0, ScreenHeight, ScreenWidth, 260)];
    dialogView.backgroundColor = [UIColor colorWithHexString:@"f2f2f2"];
    dialogView.tag = 111;
    dialogView.hidden = YES;
    
    UIButton * cancle = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, 60, 30)];
    [cancle setTitle:@"取消" forState:UIControlStateNormal];
    cancle.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [cancle addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * ok = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 70, 10, 60, 30)];
    ok.tag = 55;
    ok.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [ok setTitle:@"确定" forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [ok addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIPickerView *pickView1 = [[UIPickerView alloc]initWithFrame:CGRectMake(10, 40,(ScreenWidth - 20) , 200)];
    //pickView1.backgroundColor = [UIColor greenColor];
    
    
    

    
    pickView1.showsSelectionIndicator = YES;
    
   
    
    [dialogView addSubview:cancle];
    [dialogView addSubview:ok];
    [dialogView addSubview:pickView1];
    
    [self.view addSubview:dialogView];
    
    pickView1.dataSource = self;
    pickView1.delegate = self;

    

    
    [pickView1 selectRow:0 inComponent:0 animated:NO];
    [pickView1 selectRow:result inComponent:1 animated:NO];
    [pickView1 selectRow:48 inComponent:2 animated:NO];
    [self pickerView:pickView1 didSelectRow:0 inComponent:0];
    [self pickerView:pickView1 didSelectRow:result inComponent:1];
    [self pickerView:pickView1 didSelectRow:48 inComponent:2];

}

-(void)dialogBtn:(UIButton *) button{
    [self showTimeView:button];
    if (button.tag == 55) {
      //  self.oppointBtn.titleLabel.text = [NSString stringWithFormat:@"%@年%@%@",self.myear,self.monthDay,self.mTime];
        
        NSString *dateStr = [NSString stringWithFormat:@"%@年%@ %@",self.myear,self.monthDay,self.mTime];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
        NSDate *date = [formatter dateFromString:dateStr];
        
        if([[NSDate date] compare:date] == NSOrderedAscending){
            
            self.limitBtn.enabled = YES;
            [self.oppointBtn setTitle:[NSString stringWithFormat:@"%@年%@%@",self.myear,self.monthDay,self.mTime] forState:UIControlStateNormal];
        }else{
            [MBProgressHUD showError:@"预约时间不能早于当前时间"];
        }
            
        
    }
}

-(void)limitBtnClick{
    NSString *dateStr = [NSString stringWithFormat:@"%@年%@ %@",self.myear,self.monthDay,self.mTime];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
    NSDate *date = [formatter dateFromString:dateStr];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *userId = [UserDefaultUtil getUserId];
    NSString * appDate = [formatter stringFromDate:date];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:userId forKey:@"identifier"];
    [dic setObject:_serviceNo forKey:@"serviceNo"];
    [dic setObject:appDate forKey:@"Appointment_date"];
    [dic setObject:_note_text.text forKey:@"notes"];
    
    [dic setObject:[NSString stringWithFormat:@"%f",_lon] forKey:@"lon"];
    [dic setObject:[NSString stringWithFormat:@"%f",_lat] forKey:@"lat"];
    [dic setObject:_type forKey:@"type"];
    
    
    HttpReauestParam *param = [[HttpReauestParam alloc] initWithData:@"order_appointment_operator" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    [MBProgressHUD showMessage:@"预约时间"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        [MBProgressHUD hideHUD];

        if ([data[@"success"] boolValue]) {
            [MBProgressHUD showSuccess:@"预约成功"];
            [self.navigationController popViewControllerAnimated:YES];

        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
       
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}

-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
@end
